const Koa = require("koa");
const Router = require("koa-router");

const {
  execSync
} = require("child_process");
const JSZIP = require("jszip");
const {
  resolve
} = require("path");
const fs = require("fs");
const sendFile = require("koa-sendfile")

const {
  pushZip
} = require("./uitls/util")

const serve = require('koa-static');

const app = new Koa();
const router = new Router();

// app.use(serve(resolve(__dirname, "./form-builder/dist/")))

app.use(async (ctx, next) => {
  console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
  await next()
});

/**
 * 打包项目demo（app-source项目）
 */
router.get("/bundleApp", async (ctx, next) => {
  await execSync("cd app-source && npm run build")
  const zip = new JSZIP();
  pushZip(fs, zip, resolve(__dirname, "app-source/dist"));

  const content = await zip.generateAsync({
    type: "nodebuffer",
    compression: "DEFLATE",
    compressionOptions: {
      level: 9
    }
  })
  const err = fs.writeFileSync(resolve(__dirname, "app-source/app.zip"), content)
  if (err) throw err;
  await sendFile(ctx, resolve(__dirname, "app-source/app.zip"))
})

/**
 * 打包form-builder项目并返回打包结果
 */
router.get("/drag.html", async (ctx, next) => {
  execSync("cd form-builder && npm run build")
  app.use(serve(resolve(__dirname, "./form-builder/dist/")))
  await sendFile(ctx, resolve(__dirname, "form-builder/dist/index.html"))
})

app.use(router.routes());

app.listen(3000);
console.log("http://localhost:3000")